package com.eden.manage.service;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.eden.manage.dto.PageComDto;
import com.eden.manage.dto.PlatDto;
import com.eden.manage.mapper.EdenPlatMapper;
import com.eden.manage.model.EdenPlat;
import com.eden.manage.req.query.PlatQuery;
import com.eden.manage.utils.mapstruct.PlatStructUtils;
import eden.api.common.enums.PlatStatusEnum;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class PlatService {

    private final EdenPlatMapper edenPlatMapper;

    public PageComDto<PlatDto> pageList(PlatQuery platQuery){
        PageComDto<PlatDto> pageDto = new PageComDto();
        int count = edenPlatMapper.countByPage(platQuery);
        if(count > 0){
            List<PlatDto> platDtos = edenPlatMapper.selectPageList(platQuery);
            pageDto.setList(platDtos);
        }
        pageDto.setCount(count);
        return pageDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public void savePlat(PlatDto platDto){
        LocalDateTime now = LocalDateTime.now();
        EdenPlat edenPlat = PlatStructUtils.INSTANCE.convertDtoToDB(platDto);
        edenPlat.setUpdateTime(now);
        if(edenPlat.getId() == null ||edenPlat.getId()<=0){
            edenPlat.setId(IdWorker.getId());
            if(StringUtils.isEmpty(edenPlat.getThirdPlatId())){
                edenPlat.setThirdPlatId(String.valueOf(edenPlat.getId()));
            }
            edenPlat.setStatus(PlatStatusEnum.NO_OPEN.getCode());
            edenPlat.setCreateTime(now);
            edenPlatMapper.insert(edenPlat);
        }else{
            if(StringUtils.isEmpty(edenPlat.getThirdPlatId())){
                edenPlat.setThirdPlatId(String.valueOf(edenPlat.getId()));
            }
            edenPlatMapper.updateById(edenPlat);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void updatePlatStatus(PlatDto platDto){
        EdenPlat edenPlat = edenPlatMapper.selectById(platDto.getId());
        if(edenPlat.getStatus().equals(PlatStatusEnum.NO_OPEN.getCode())){
            edenPlatMapper.updateOpenStatus(platDto);
        }else{
            edenPlatMapper.updateStatus(platDto);
        }
    }
}
